<?php

namespace App\Admin\Controllers;

use App\Admin\Forms\IPSearch;
use App\Http\Controllers\Controller;
use App\Jobs\QueryIpStatus;
use Encore\Admin\Admin;
use Encore\Admin\Controllers\Dashboard;
use Encore\Admin\Form\Field;
use Encore\Admin\Layout\Column;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class HomeController extends Controller
{
    public function index(Content $content)
    {
        return $content
            ->title('Dashboard')
            ->description('Description...')
            ->row(Dashboard::title())
            ->row(function (Row $row) {

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::environment());
                });

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::extensions());
                });

                $row->column(4, function (Column $column) {
                    $column->append(Dashboard::dependencies());
                });
            });
    }

    // 页面
    public function ipSearch2(Content $content)
    {
        // 将原来的IPSearch类中初始化页面的相关操作放到自定义的页面中来，这里不再赘述
        $form = new Form();
        $form->action('#')->attribute(['name' => 'ip_search']);
        $form->ip('IP')->attribute(['name' => 'ip'])->rules('required');
        $form->select('type')->attribute(['name' => 'type'])->options([1 => 'json', 2 => 'plain'])->rules('required');
        $form->hidden('count')->attribute(['name' => 'count'])->value(0);
        $form->textarea('result');
        $form->textarea('link');
        $form->disableSubmit();
        $form->disableReset();
        $html = $form->render();
        return $content->title('IP查询')
            ->view('ip_search.ip_search', ['html' => $html]);
    }

    // 原来的查询ip的方法
    public function ipSearchAction(Request $request)
    {
        $ip = $request->get('ip');
        $type = $request->get('type');

        if (!$ip || !$type) {
            return response()->json(['status' => 0, 'message' => 'data error']);
        }

        $count = $request->get('count', 0);
        $count++;
        $url = 'http://ip-api.com/json/' . $ip;
        $result = $this->curlGet($url);
        if (!$result) {
            $result = 'request time out';
        }
        $str = 'abc';
        if (strstr(json_encode($result), $str) !== false || $count === 9) {
            $result = '@查询失败';
        }

        return response()->json(['status' => 1, 'message' => 'success', 'data' => [
            'ip' => $ip,
            'type' => $type,
            'count' => $count,
            'result' => $result
        ]]);
    }

    // 将检测联通性的操作放入队列中，因为是异步操作，使用的是redis连接队列
    public function ipLinkStatus(Request $request)
    {
        $ip = $request->get('ip');
        // QueryIpStatus在 app/Jobs文件夹中，通过命令 php artisan make:job QueryIpStatus在 可以创建
        // 可以通过 QueryIpStatus::dispatch($ip)->onConnect('sync');改成同步操作
        QueryIpStatus::dispatch($ip);
        return response()->json(['status' => 1, 'message' => 'success']);
    }


    // 查询检测联通性的结果
    public function ipLinkStatusQuery(Request $request)
    {
        $ip = $request->get('ip');
        $result = Redis::get($ip);
        if(!$result){
            return response()->json(['status' => 1, 'message' => 'query','continue'=>1]);
        }else{
            return response()->json(['status' => 1, 'message' => 'success','continue'=>0,'result'=>$result]);
        }
    }

// 已废弃
//    public function ipSearch(Content $content)
//    {
//        $ipSearch = new IPSearch();
//
//        $content->title('IP查询')->body($ipSearch);
//
//        if ($result = session('result')) {
//            $json = json_encode($result);
//            $data = session('data');
//            $ip = $data['ip'];
//            $type = $data['type'];
//            $count = session('count');
//
//            $test = <<<EOT
//<script>
//let a = '$json';
//let ipval = '$ip';
//let typeval = '$type';
//let countval = '$count';
//let ele = $('textarea')[0]
//let ip = $('input[name=ip]')[0]
//let type = $('select[name=type]')[0]
//let count = $('input[name=count]')[0]
//$(ele).val(a)
//$(ip).val(ipval)
//$(type).val(typeval)
//$(count).val(countval)
//let formNode = $('form[name=ip_search]')[0]
//if(countval <= 9){
// let i = setTimeout(function() {
//    console.log(countval)
//    $(formNode).submit()
//},10000)
//}
//</script>
//EOT;
//            $content->body($test);
//        }
//
//        return $content;
//    }

    public function curlGet($url)
    {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
//        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}
